package com.bobbyjjw.session;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import com.bobbyjjw.common.Common;

/**
 * 测试环境下自动获得AuthCode
 * 
 * @author Bobby.Jin
 * 
 */

public class GetAuthCode {

	private static String doPostForAuthCode(String host, int port, String url,
			HashMap<String, String> parametersMap) throws Exception {
		HttpClient hc = new HttpClient();
		hc.getHostConfiguration().setHost(host, port);

		Iterator<Entry<String, String>> it = parametersMap.entrySet()
				.iterator();
		NameValuePair[] nameValuePair = new NameValuePair[parametersMap.size()];
		int i = 0;
		while (it.hasNext()) {
			Entry<String, String> e = it.next();
			nameValuePair[i++] = new NameValuePair(e.getKey(), e.getValue());
		}
		PostMethod pm = new PostMethod(url);
		pm.setRequestBody(nameValuePair);
		hc.executeMethod(pm);
		InputStream is = pm.getResponseBodyAsStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is,
				"UTF-8"));
		String line = "";
		while ((line = br.readLine()) != null
				&& (line.indexOf("autoInput") == -1))
			;
		String authCode = "";
		if (line != null && line.indexOf("autoInput") != -1) {
			int value = line.indexOf("value=") + 7;
			authCode = line.substring(value, line.substring(value)
					.indexOf("\"")
					+ value);
		}
		pm.releaseConnection();
		return authCode;
	}

	/**
	 * to Get AuthCode
	 * 
	 * @return
	 */
	public static String getAuthCode() {
		String authCode = "";
		try {
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("appkey", Common.APP_KEY);
			map.put("nick", Common.TEST_NICK);
			authCode = doPostForAuthCode(Common.TEST_HOST, 80,
					Common.TEST_PAGE, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return authCode;
	}

	public static void main(String args[]) {
		try {
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("appkey", "12015998");
			map.put("nick", "alipublic01");
			String authCode = doPostForAuthCode("open.taobao.com", 80,
					"/isv/authorize.php", map);
			System.out.println(authCode);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}